package com.liuwang.meal.ui;

import java.util.List;

import com.api.util.SendOrder;
import com.liuwang.meal.R;
import com.liuwang.meal.bean.OrderItem;
import com.liuwang.meal.bean.User;
import com.liuwang.meal.manager.OrderDetailManager;
import com.liuwang.meal.manager.UserManager;
import com.liuwang.meal.util.FloatApplication;
import com.liuwang.meal.util.FloatFrame;
import com.liuwang.meal.util.MyApplication;
import com.liuwang.meal.util.MyUtil;
import com.liuwang.meal.util.SharedPrefer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 订单页面
 * 
 * @author 陈江根
 */
public class OrderActivity extends Activity {
	/** 浮动窗口属性 */
	private WindowManager wm = null;
	private WindowManager.LayoutParams wmParams = null;
	private FloatFrame myFV = null;
	// 声明控件
	private ListView listview_orderDetail;
	private List<OrderItem> mData;
	private MyAdapter adapter;
	private int total_num = 0, total_prices = 0;
	private TextView textview_total_num, textview_total_prices;
	private Button button_order_submit, button_order_pay, button_online_pay,
			button_order_back, button_success_pay;
	private Integer type_id = 1;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String id = (String) msg.obj;
				if (id.equals("1")) {
					Toast.makeText(getApplicationContext(), "下单成功", 1).show();
					bindOrderDetails();
				} else {
					Toast.makeText(getApplicationContext(), "下单失败，请稍候再试", 1)
							.show();
				}
				break;
			case 0:
				Toast.makeText(getApplicationContext(), "连接网络失败", 1).show();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order);
		MyApplication.getInstance().addActivity(this);// 添加当前Activity到Activity容器
		type_id = getIntent().getExtras().getInt("type_id");

		textview_total_num = (TextView) findViewById(R.id.listview_textview_total_num);
		textview_total_prices = (TextView) findViewById(R.id.listview_textview_total_prices);
		button_order_submit = (Button) findViewById(R.id.button_order_submit);
		button_order_pay = (Button) findViewById(R.id.button_order_pay);
		button_online_pay = (Button) findViewById(R.id.button_online_pay);
		button_order_back = (Button) findViewById(R.id.button_order_back);
		button_success_pay = (Button) findViewById(R.id.button_success_pay);

		// 为列表ListView绑定数据
		bindOrderDetails();

		createFloatView();
	}

	public void submitOrder(View v) {

		new OrderDetailManager(OrderActivity.this).updateState(0, 1);
		bindOrderDetails();
		submitOrder();

	}

	public void payOnline(View view) {
		int total[] = new OrderDetailManager(this).queryTotal();
		try {
			SharedPrefer.SaveSumPrice(getApplicationContext(), total[0]);
		} catch (Exception e) {
			e.printStackTrace();
		}
		new OrderDetailManager(OrderActivity.this).updateState(1, 4);
		bindOrderDetails();

		Intent intent = new Intent(OrderActivity.this, PayActivity.class);
		intent.putExtra("type_id", type_id);
		startActivityForResult(intent, 0);

	}

	public void payOrder(View view) {

		new OrderDetailManager(OrderActivity.this).updateState(1, 4);
		bindOrderDetails();
		Toast.makeText(getApplicationContext(), "前台正在打印结账单,请移步至前台结账", 0).show();
		// OrderDetailManager dd = new
		// OrderDetailManager(getApplicationContext());

	}

	public void paySuccess(View view) {
		
		Intent intent = new Intent(OrderActivity.this, adminPayActivity.class);
		intent.putExtra("type_id", type_id);
		startActivityForResult(intent, 0);
		
		
//		Toast.makeText(getApplicationContext(), "完成结账", 1).show();
//		new OrderDetailManager(OrderActivity.this).updateState(1, 5);
//		bindOrderDetails();
//		OrderDetailManager dd = new OrderDetailManager(getApplicationContext());
//		dd.truncate();
	}

	public void orderBack(View v) {
		// 返回到主菜单页面
		Intent intent = new Intent(OrderActivity.this, MenuActivity.class);
		intent.putExtra("type_id", type_id);
		setResult(RESULT_OK, intent);
		finish();
	}

	/** 创建悬浮窗口 */
	private void createFloatView() {
		Point windowSize = new Point();
		windowSize.x = this.getWindowManager().getDefaultDisplay().getWidth();
		windowSize.y = this.getWindowManager().getDefaultDisplay().getHeight();
		myFV = new FloatFrame(getApplicationContext());

		wm = (WindowManager) getApplicationContext().getSystemService(
				Context.WINDOW_SERVICE);

		wmParams = ((FloatApplication) getApplication()).getWmParams();

		wmParams.type = 2003;
		wmParams.format = PixelFormat.RGBA_8888;

		wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
				| LayoutParams.FLAG_NOT_FOCUSABLE;

		wmParams.gravity = Gravity.LEFT | Gravity.TOP;

		wmParams.x = windowSize.x;
		wmParams.y = windowSize.y / 2;

		wmParams.width = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;// 40;
		wmParams.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;// 40;

		// 显示myFloatView图像
		wm.addView(myFV, wmParams);
	}

	public void submitOrder() {
		String goodOrders = null;
		int eatNum = SharedPrefer.ReadEatNum(getApplicationContext());
		int tableNo = SharedPrefer.ReadTableNo(getApplicationContext());
		int userId = SharedPrefer.ReadUserId(getApplicationContext());
		String dd = ":";
		String hh = "@";
		int len = mData.size();
		for (int i = 0; i < len; i++) {
			OrderItem item = mData.get(i);

			String name = item.getName();
			int num = item.getNum();
			int price = item.getPrice();
			if (goodOrders==null) {
				goodOrders = userId + dd + tableNo + dd + eatNum + dd + num
						+ dd + price + dd + name + hh;
			} else {
				goodOrders = goodOrders + userId + dd + tableNo + dd + eatNum
						+ dd + num + dd + price + dd + name + hh;
			}
			System.out.println("得到的菜品goodOrders：" + goodOrders);
		}
		final String goodOrder = goodOrders;
		System.out.println("得到的菜品goodOrder：" + goodOrders);
		new Thread() {
			@Override
			public void run() {
				Message msg = new Message();
				SendOrder send = new SendOrder();
				super.run();
				try {
					String html = send.saveOrder(goodOrder);
					msg.what = 1;
					msg.obj = html;
					handler.sendMessage(msg);

				} catch (Exception e) {
					e.printStackTrace();
					msg.what = 0;
					handler.sendMessage(msg);
				}
			}
		}.start();

	}

	private void bindOrderDetails() {
		// 通过订单详细管理类获取订单信息
		mData = new OrderDetailManager(this).queryOrderItems();

		MyAdapter adapter = new MyAdapter(this);
		//
		total_num = 0;
		total_prices = 0;
		// 为ListView绑定数据
		listview_orderDetail = (ListView) findViewById(R.id.listview_orderDetail);
		listview_orderDetail.setAdapter(adapter);

		if (new OrderDetailManager(OrderActivity.this).queryByState(0)) {
			button_order_submit.setVisibility(View.VISIBLE);
			button_order_pay.setVisibility(View.GONE);
			button_online_pay.setVisibility(View.GONE);
			button_success_pay.setVisibility(View.GONE);
			button_order_back.setVisibility(View.VISIBLE);
		} else {
			button_order_submit.setVisibility(View.GONE);
			button_order_back.setVisibility(View.VISIBLE);
		}
		if (new OrderDetailManager(OrderActivity.this).queryByState(1)) {

			button_order_pay.setVisibility(View.VISIBLE);
			button_online_pay.setVisibility(View.VISIBLE);
			button_success_pay.setVisibility(View.GONE);

		}

		if (new OrderDetailManager(OrderActivity.this).queryByState(4)) {

			button_order_pay.setVisibility(View.GONE);
			button_online_pay.setVisibility(View.VISIBLE);
			button_success_pay.setVisibility(View.VISIBLE);

		}
		if (new OrderDetailManager(OrderActivity.this).queryByState(5)) {

			button_order_pay.setVisibility(View.GONE);
			button_online_pay.setVisibility(View.GONE);
			button_success_pay.setVisibility(View.GONE);

			// OrderDetailManager dd = new
			// OrderDetailManager(getApplicationContext());
			// dd.truncate();

		}
		// else {
		// // button_online_pay.setVisibility(View.GONE);
		// button_success_pay.setVisibility(View.VISIBLE);
		// button_order_back.setVisibility(View.VISIBLE);
		//
		// }

		// 绑定总订单价格、总订单数量
		int total[] = new OrderDetailManager(this).queryTotal();
		textview_total_prices.setText(total[0] + "元");
		textview_total_num.setText(total[1] + "");

	}

	public class MyAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getView(int, android.view.View,
		 * android.view.ViewGroup)
		 */
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.row_listview_content,
						null);
			}
			// 给控件赋值
			((TextView) convertView.findViewById(R.id.listview_textview_id))
					.setText((position + 1) + "");
			((TextView) convertView.findViewById(R.id.listview_textview_name))
					.setText(mData.get(position).getName());
			((TextView) convertView.findViewById(R.id.listview_textview_price))
					.setText(mData.get(position).getPrice() + "元/"
							+ mData.get(position).getUnit());
			((TextView) convertView.findViewById(R.id.listview_textview_num))
					.setText(mData.get(position).getNum().toString());
			((TextView) convertView.findViewById(R.id.listview_textview_prices))
					.setText((mData.get(position).getPrice() * mData.get(
							position).getNum())
							+ "");
			((TextView) convertView.findViewById(R.id.listview_textview_remark))
					.setText(mData.get(position).getRemark());

			final Button button_add = ((Button) convertView
					.findViewById(R.id.button_add));
			// 已结账，不显示
			if (new OrderDetailManager(OrderActivity.this).queryState(mData
					.get(position).get_id()) >= 4) {
				button_add.setVisibility(View.INVISIBLE);
			}
			button_add.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (new OrderDetailManager(OrderActivity.this).query(mData
							.get(position).getMenuID())
							&& 0 == new OrderDetailManager(OrderActivity.this)
									.queryState(mData.get(position).get_id())) {// 已存在、状态为0
						// 数量加1
						new OrderDetailManager(OrderActivity.this).updateNum(
								mData.get(position).get_id(), 1);
					} else {
						int id;
						if ((id = new OrderDetailManager(OrderActivity.this)
								.query(mData.get(position).getMenuID(), 0)) > -1) {
							// 数量加1
							new OrderDetailManager(OrderActivity.this)
									.updateNum(id, 1);
						} else {
							// 订单项加1
							new OrderDetailManager(OrderActivity.this)
									.addOrderItem(mData.get(position)
											.getMenuID());
						}
					}
					// 重新绑定数据
					bindOrderDetails();

				}
			});
			final Button button_sub = ((Button) convertView
					.findViewById(R.id.button_sub));
			// 小于2 、 已下单，不显示
			if ((mData.get(position).getNum() < 2)
					|| (0 != new OrderDetailManager(OrderActivity.this)
							.queryState(mData.get(position).get_id()))) {
				button_sub.setVisibility(View.INVISIBLE);
			}
			button_sub.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// 数量减1
					new OrderDetailManager(OrderActivity.this).updateNum(mData
							.get(position).get_id(), -1);
					// 重新绑定数据
					bindOrderDetails();
				}
			});

			ImageView imageview_remark = ((ImageView) convertView
					.findViewById(R.id.listview_imageview_remark));
			imageview_remark
					.setBackgroundResource(android.R.drawable.ic_input_add);
			imageview_remark.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// 取得自定义View
					LayoutInflater layoutInflater = LayoutInflater
							.from(OrderActivity.this);
					final View order_remark_View = layoutInflater.inflate(
							R.layout.order_remark, null);

					Dialog alertDialog = new AlertDialog.Builder(
							OrderActivity.this)
							.setTitle("给菜添加说明注释")
							.setIcon(R.drawable.call)
							.setView(order_remark_View)
							.setPositiveButton("提交",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// 获取选中的单选按钮的值
											String radio_checkValue = ((RadioButton) order_remark_View
													.findViewById(((RadioGroup) order_remark_View
															.findViewById(R.id.radioGroup_Spicy))
															.getCheckedRadioButtonId()))
													.getText().toString();
											// 获取输入框中的值
											String editText_orderRemark = ((TextView) order_remark_View
													.findViewById(R.id.editText_orderRemark))
													.getText().toString();
											// 向数据库修改备注信息
											new OrderDetailManager(
													OrderActivity.this)
													.updateRemark(
															mData.get(position)
																	.get_id(),
															radio_checkValue
																	+ ","
																	+ editText_orderRemark);
											// 重新绑定数据
											bindOrderDetails();
										}
									})
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {

										}
									}).create();
					alertDialog.show();
				}
			});
			ImageView imageview_delete = ((ImageView) convertView
					.findViewById(R.id.listview_imageview_delete));
			imageview_delete
					.setBackgroundResource(android.R.drawable.ic_delete);
			imageview_delete.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							OrderActivity.this);
					builder.setTitle("删除订单项")
							.setMessage("你确定要删除吗？")
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// 删除数据库中的订单项
											new OrderDetailManager(
													OrderActivity.this)
													.delete(mData.get(position)
															.get_id());
											// mData.remove(position);
											// notifyDataSetChanged();
											// 重新绑定数据
											bindOrderDetails();
										}
									})
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.dismiss();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();

				}
			});
			imageview_remark.setVisibility(View.INVISIBLE);
			imageview_delete.setVisibility(View.INVISIBLE);
			String State = "";
			switch (mData.get(position).getState()) {
			case 0:
				State = "待提交";
				imageview_remark.setVisibility(View.VISIBLE);
				imageview_delete.setVisibility(View.VISIBLE);
				break;
			case 1:
				State = "已下单";
				break;
			case 2:
				State = "烹饪中";
				break;
			case 3:
				State = "出锅";
				break;
			case 4:
				State = "结账中";
				break;
			case 5:
				State = "已结账";
				break;
			default:
				State = "无";
				break;
			}
			((TextView) convertView.findViewById(R.id.listview_textview_state))
					.setText(State);

			return convertView;
		}
	}

	// 捕捉按键事件
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 返回到主菜单页面
			Intent intent = new Intent(OrderActivity.this, MenuActivity.class);
			intent.putExtra("type_id", type_id);
			setResult(RESULT_OK, intent);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 建立菜单选项
	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		getMenuInflater().inflate(R.menu.options_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	// 处理菜单选项
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.quit:
			// 取得自定义View
			LayoutInflater layoutInflater = LayoutInflater
					.from(OrderActivity.this);
			final View logout_View = layoutInflater.inflate(R.layout.logout,
					null);

			Dialog alertDialog = new AlertDialog.Builder(OrderActivity.this)
					.setTitle("确认退出吗？")
					.setIcon(R.drawable.call)
					.setView(logout_View)
					.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// 获得服务员工号,查找本地用户信息
									String account = findUserMsg();
									// 获得密码
									String password = ((TextView) logout_View
											.findViewById(R.id.edittext_logout_password))
											.getText().toString();

									User user = new UserManager(
											OrderActivity.this).query(account,
											password);
									if (user != null) {
										// 清空订单信息
										new OrderDetailManager(
												OrderActivity.this).truncate();
										// 删除本地用户信息
										deleteUserMsg();
										// 关闭背景音乐
										stopService(new Intent(
												"com.liuwang.meal.MUSIC"));
										// 关闭所有Activity
										MyApplication.getInstance().exit();

									} else {
										MyUtil.showDialog(OrderActivity.this,
												"密码错误，退出失败");
									}
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {

								}
							}).create();
			alertDialog.show();

			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// 查找配置文件中的用户信息
	private String findUserMsg() {
		// 共享信息
		SharedPreferences sp = getSharedPreferences("user_msg",
				MODE_WORLD_WRITEABLE);
		return sp.getString("account", "");
	}

	// 清空配置文件中的用户信息
	private void deleteUserMsg() {
		// 共享信息
		SharedPreferences sp = getSharedPreferences("user_msg",
				MODE_WORLD_WRITEABLE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("account", "");
		editor.commit();
	}
}
